package servlet;

import bean.User;
import dao.JdbcUserDaoImpl;
import dao.UserDao;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetUserInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(df.format(new Date()) + ":GetUserInfo");
        User user = null;
        String sessionID = req.getSession().getId();
        Jedis jedis = new Jedis("127.0.0.1",6379);
        Writer writer = resp.getWriter();
        if(jedis.exists(sessionID))
        {
            String username = jedis.get(sessionID);
            UserDao userDao = new JdbcUserDaoImpl();
            user = userDao.getAllUserInfo(username);
            ((PrintWriter) writer).print("{\"name\":\""+user.getUsername()+"\",\"age\":"+user.getAge()+",\"sex\":\""+user.getGender()+"\"}");
        }
        else
        {
            ((PrintWriter) writer).print("no");
        }

    }

}
